//
//  Moya.swift
//  EPHome
//
//  Created by liujianlong on 2022/8/26.
//

import Foundation
import Moya

let url_appStore = URL(string: "https://apps.apple.com/cn/app/ai-health/id1546420870")

enum EPApi{
    //MARK: - 用户模块
    case checkUpdate(_ dict:[String:Any])
    case download(_ http:String, _ fileName:String)
    ///获取所有产品编号
    case productNumber
    ///记录激活产品
    case reactive(_ dict:[String:Any])
    ///上传最后一次更新记录(用于救砖)
    case recordDeviceUpload(_ dict:[String:Any])
    ///区分APP是国内版本还是国外版本，根据是国内还是国外的APP版本，返回能搜索到的广播ID，（broadcastid）
    ///countryType=0 国内
    ///countryType=1国外
    ///countryType=2 通用
    case gegBroad(_ countryType:Int)
    // 获取想要存储的文件路径
    var localLocation: URL {
        switch self {
        case .download(let http ,let fileName):
            let filePath = FileManager.default.temporaryDirectory
            return filePath.appendingPathComponent(fileName)
        default:
            return URL(fileURLWithPath: "")
        }
    }
    // 封装下下载路径
    var downloadDestination: DownloadDestination {
        // `createIntermediateDirectories` will create directories in file path
        return { _, _ in return (self.localLocation, [.removePreviousFile, .createIntermediateDirectories]) }
    }
}

extension EPApi:TargetType{
    ///baseurl
    var baseURL: URL{
        switch self{
        case let .download(http,_):
            return URL(string:http) ?? URL(fileURLWithPath: "")
        default:
            return URL(string: "http://47.113.195.211:8091/")!
        }
    }
    ///公共请求头
    var headers: [String : String]? {
        ///返回nil，后台自动识别是json，还是表单格式
        return nil
        //        return ["Content-type":"application/json"]
        //        return ["Content-Type": "application/x-www-form-urlencoded"]
    }
    ///请求api的路径
    var path: String {
        switch self{
        case .checkUpdate:///检查固件更新
            return "checkUpdate"
        case let .download(file):
            // return "/firmware/download/"+file
            return ""
        case .productNumber:///获取所有产品编号
            return "productNumberList"
        case .reactive:
            return "cdkey/record/save"
        case .recordDeviceUpload:
            return "recordDeviceUpload"
        case .gegBroad:
            return "getBroadcastId"
        }
    }
    
    /// 请求方式
    var method: Moya.Method {
        switch self{
            //MARK: - 用户模块
        case .checkUpdate:
            return .post
        case .download:
            return .get
        case .productNumber:
            return .get
        case .reactive:
            return .post
        case .recordDeviceUpload:
            return .get
        case .gegBroad:
            return .get
        }
    }
    /// 解析格式
    var sampleData: Data{
        return "{}".data(using: String.Encoding.utf8)!
        //return Data(base64Encoded: "just for test")!
    }
    
    
    var task: Task {
        switch self{
        case let.checkUpdate(dict):
            return .requestParameters(parameters:dict, encoding: JSONEncoding.default)
        case .download:
            return .downloadDestination(downloadDestination)
        case .productNumber:
            return .requestPlain
        case let .reactive(dict):
            return .requestParameters(parameters:dict, encoding: URLEncoding.default)
        case let .recordDeviceUpload(dict):
            return .requestParameters(parameters:dict, encoding: URLEncoding.default)
        case let .gegBroad(countryType):
            return .requestParameters(parameters:["countryType":countryType], encoding: URLEncoding.default)
        }
    }
}


//插件写法
class loadingPlugin:PluginType{
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        return request
    }
    func willSend(_ request: RequestType, target: TargetType) {
    }
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
    }
    
    func process(_ result: Result<Response, MoyaError>, target: TargetType) -> Result<Response, MoyaError> {
        // 在这里对请求进行统一处理（比如有加密，可以统一进行解密）
        //        if let value = result.value, let _ = try? JSONSerialization.jsonObject(with: value.data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any] {
        //
        //            let ob = ["code": 666, "description": "牛逼大发了"] as [String : Any]
        //            let data = try! JSONSerialization.data(withJSONObject: ob, options: JSONSerialization.WritingOptions.fragmentsAllowed)
        //
        //            let response = Response(statusCode: value.statusCode, data: data, request: value.request, response: value.response)
        //
        //            let res = Result<Response, MoyaError>.init(value: response)
        //            return res
        //        }
        return result
    }
    
}


